package com.itheima.intercept;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyIntercept implements HandlerInterceptor {

    @Autowired
    private JedisPool jedisPool;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取到所有的cookie值
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            //数据不为空
            for (Cookie cookie : cookies) {
                //判断是否已经登录过
                boolean result = cookie.getName().equals("telephone_login");
                if (result){
                    String value = cookie.getValue();
                    //获取到Redis中的Json数据
                    Jedis resource = jedisPool.getResource();
                    String member = resource.get("telephone");
                    resource.close();

                    if (member == null){
                        ServletOutputStream outputStream = response.getOutputStream();
                        response.setContentType("application/json");

                        outputStream.write("{\"data\":null,\"flag\":false,\"message\":\"登录过期\"}".getBytes());
                        outputStream.flush();
                        outputStream.close();
                        return false;
                    }

                    return true;
                }
            }
        }
        return false;
    }
}
